package ru.aptu.gsp_banking.service_impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ru.aptu.gsp_banking.dao.AccountDAO;
import ru.aptu.gsp_banking.dao.TransactionDAO;
import ru.aptu.gsp_banking.domain.Account;
import ru.aptu.gsp_banking.domain.MoneyTransfer;
import ru.aptu.gsp_banking.domain.Transaction;
import ru.aptu.gsp_banking.service.CurrencyService;
import ru.aptu.gsp_banking.service.MoneyTransferService;

/**
 * Created by IntelliJ IDEA.
 * User: alex
 * Date: 1/20/12
 * Time: 3:22 PM
 */

@Service
public class MoneyTransferServiceImpl implements MoneyTransferService {

    @Autowired
    private TransactionDAO transactionDAO;

    @Autowired
    private AccountDAO accountDAO;

    @Autowired
    private CurrencyService currencyService;

    @Transactional
    public boolean submitMoneyTransfer(MoneyTransfer moneyTransfer) {
        Account accountFrom = accountDAO.getAccountById(moneyTransfer.getAccountIdFrom());

        if (accountFrom.getBalance()
                < currencyService.convert(moneyTransfer.getAmount(), moneyTransfer.getCurrency(), accountFrom.getCurrency())
                || moneyTransfer.getAmount() <= 0) {
            return false;
        }

        Transaction transactionFrom = new Transaction(
                moneyTransfer.getAccountIdFrom(), -moneyTransfer.getAmount(), moneyTransfer.getCurrency(),
                "Money transfer");
        Transaction transactionTo = new Transaction(
                moneyTransfer.getAccountIdTo(), moneyTransfer.getAmount(), moneyTransfer.getCurrency(),
                "Money transfer");

        submit(moneyTransfer);
        return true;
    }

    public void submit(MoneyTransfer moneyTransfer) {
        Transaction transactionFrom = new Transaction(
                moneyTransfer.getAccountIdFrom(), -moneyTransfer.getAmount(), moneyTransfer.getCurrency(),
                "Money transfer");
        Transaction transactionTo = new Transaction(
                moneyTransfer.getAccountIdTo(), moneyTransfer.getAmount(), moneyTransfer.getCurrency(),
                "Money transfer");

        saveTransaction(transactionFrom);
        saveTransaction(transactionTo);
    }

    public void saveTransaction(Transaction transaction) {
        transactionDAO.saveTransaction(transaction);
    }
}
